from PIL import Image, ImageEnhance
import os
import random
import string


def generate_random_filename():
    """生成随机文件名：4大写字母 + 4数字"""
    # letters = ''.join(random.choices(string.ascii_uppercase, k=4))
    letters = 'IMG_'
    numbers = ''.join(random.choices(string.digits, k=4))
    return f"{letters}{numbers}.jpg"


def adjust_image_properties(img, brightness=0.8, contrast=0.8, saturation=0.8):
    """调整图像属性"""
    # 亮度调整
    enhancer = ImageEnhance.Brightness(img)
    img = enhancer.enhance(brightness)

    # # 对比度调整
    enhancer = ImageEnhance.Contrast(img)
    img = enhancer.enhance(contrast)

    # # 饱和度调整
    enhancer = ImageEnhance.Color(img)
    img = enhancer.enhance(saturation)

    return img


def webp_to_jpg(input_path, output_folder=None, quality=85):
    """
    增强版WebP转JPG功能
    参数：
    - brightness: 亮度系数 (0.0-1.0)
    - contrast: 对比度系数 (0.0-1.0)
    - saturation: 饱和度系数 (0.0-1.0)
    """
    try:
        with Image.open(input_path) as img:
            # 处理透明通道
            if img.mode in ('RGBA', 'LA'):
                background = Image.new('RGB', img.size, (255, 255, 255))
                background.paste(img, mask=img.split()[-1])
                img = background

            # 应用图像调整（参数设置为80%）
            img = adjust_image_properties(img,
                                          brightness=0.9,
                                          contrast=0.9,
                                          saturation=1)

            # 生成输出路径
            output_path = os.path.join(
                output_folder if output_folder else os.path.dirname(input_path),
                generate_random_filename()
            )

            os.makedirs(os.path.dirname(output_path), exist_ok=True)
            img.convert('RGB').save(output_path, "JPEG", quality=quality)
            print(f"转换成功: {output_path}")
            return True

    except Exception as e:
        print(f"转换失败: {str(e)}")
        return False


def batch_convert_webp(input_folder, output_folder):
    """批量转换增强版"""
    valid_extensions = ('.webp', '.WEBP')
    for filename in os.listdir(input_folder):
        if filename.endswith(valid_extensions):
            webp_to_jpg(
                os.path.join(input_folder, filename),
                output_folder,
                quality=90  # 推荐批量使用较高品质
            )


if __name__ == "__main__":
    # 单文件测试
    # webp_to_jpg("test.webp", "output")

    # 批量转换
    batch_convert_webp("D:/Desk/123/webp", "D:/Desk/123/jpg/")